package cn.tedu.boot21.controller;


import cn.tedu.boot21.entity.User;
import cn.tedu.boot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@Controller
public class UserController {


    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user, HttpServletResponse response) {
        try (Connection connection = DBUtils.getConn()){
            String sql = "select id from user where username = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return "<h1>用户名已存在,注册失败</h1>\n" + "<a href=\"reg.html\">重新注册</a>\n";
            }else {
                String sql1 = "insert into user values(null ,?,?,?)";
                ps = connection.prepareStatement(sql1);
                ps.setString(1, user.getUsername());
                ps.setString(2,user.getPassword());
                ps.setString(3,user.getNick());
                ps.executeUpdate();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return "<h1>注册成功!</h1><h1><a href=\"login.html\">登录</a></h1>\n";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String username,String password,HttpServletResponse response){
        try (Connection connection = DBUtils.getConn()){
            String sql = "select password from user where username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                String pw = rs.getString(1);
                if (pw.equals(password)) {
                    response.sendRedirect("/login_success.html");
                    return "登录成功!";
                }else {
                    return "密码错误!<a href=\"login.html\" style=\"font-size: 150px\">请重新登录</a>\n";
                }
            }
        } catch (SQLException | IOException throwables) {
            throwables.printStackTrace();
        }
        return "用户名不存在!<a href=\"reg.html\" style=\"font-size: 150px\">请重新注册</a>\n";
    }




}
